"""
媒体播放例子的UI层。
"""

from typing import Any, Callable, Final
from elio import core  # type: ignore
from elio.core.base import BaseSessionParentType  # type: ignore

TEST_AUDIO_URL: Final[str] = 'https://img.tukuppt.com/newpreview_music/09/01/98/5c8a2753cef8972878.mp3'

class PlayerLayer(core.AutoRecycleLayer[core.Activity]):
    player: core.MediaPlayer
    btn_play: core.WidgetButton
    btn_forward: core.WidgetButton
    btn_rewind: core.WidgetButton
    btn_close: core.WidgetButton

    async def on_create(self, *args: Any, **kwargs: dict):
        await super().on_create(*args, *kwargs)

    async def on_show(self):
        await super().on_show()
        activity = self.parent

        # 创建媒体播放器
        self.player = await core.MediaPlayer.create(activity)
        await self.player.load(TEST_AUDIO_URL)

        async def cb_close():
            """
            播放完毕事件。
            """
            await activity.pop_layer()

        await self.player.set_on_completion_listener(cb_close)

        self.btn_play = await self.create_button("播放", 100, self.cb_play)
        self.btn_forward = await self.create_button("快进", 200, self.cb_fast(5000))
        self.btn_rewind = await self.create_button("快退", 250, self.cb_fast(-5000))
        self.btn_close = await self.create_button("退出", 400, cb_close)

    async def on_hide(self):
        await super().on_hide()
        # 销毁播放器
        await self.player.destroy()

        await self.btn_play.destroy()
        await self.btn_forward.destroy()
        await self.btn_rewind.destroy()
        await self.btn_close.destroy()

    async def on_pause(self):
        await super().on_pause()

    async def on_resume(self):
        await super().on_resume()

    async def on_destroy(self, *args: Any, **kwargs: dict):
        await super().on_destroy(*args, **kwargs)

    async def create_button(self, name: str, pos_y: int, cb: Callable) -> core.WidgetButton:
        """
        创建按钮。
        :param name: 按钮文字。
        :param pos_y: 纵坐标。
        :param cb: 点击处理函数。
        :return: core.WidgetButton
        """
        activity = self.parent
        width, _ = await activity.get_screen_size()

        button = await core.WidgetButton.create(activity, width - 60, 50, 30, pos_y, name)
        await button.set_on_click_listener(cb)
        return button

    async def cb_play(self):
        """
        播放按钮的回调方法
        """
        is_playing = await self.player.is_playing()
        if is_playing:
            await self.player.pause()
        else:
            await self.player.play()

    def cb_fast(self, num: int) -> Callable:
        """
        生成快进函数。
        :param num: 快进长度
        :return: 函数对象。
        """
        async def cb():
            """
            内部使用。
            """
            cur = await self.player.current_position()
            cur += num
            await self.player.seek_to(cur)

        return cb
